package csc.fresher.finalgroupfour.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.fresher.finalgroupfour.domain.Role;

@Repository("roleDAO")
public class RoleDAO {
	@PersistenceContext
	private EntityManager em; // Entity Manager is acquired by container.
	
	/**
	 * Add a new role.
	 * @param role
	 */
	@Transactional
	public void addRole(Role role) {
		em.persist(role);
	}
	
	/**
	 * List all roles in DB.
	 * @return
	 */
	@Transactional
	public List<Role> listRoles() {
		List<Role> roles = new ArrayList<Role>();
		TypedQuery<Role> query = em.createQuery("SELECT a FROM Role a", Role.class);
		
		roles = query.getResultList();
		if (roles.size() > 0) {
			return roles;
		}
		return null;
	}
	
	/**
	 * Update a role's information
	 * @param role
	 */
	@Transactional
	public void updateRole(Role role) {
		em.merge(role);
	}
	
	/**
	 * Remove a role from database.
	 * @param role
	 */
	@Transactional
	public void deleteRole(Role role) {
		em.remove(role);
	}
	
	/**
	 * Find weather a role existed or not.
	 * @param role
	 * @return
	 */
	@Transactional
	public boolean findRole(Role role) {
		return em.contains(role);
	}
}

